import { handleSuccess, handleException, handleLoginExpire, handleTokenExpire, handleLoginAgain } from '../modules';
import { eventEmitter } from '@/common/message';
const handleFactory = (http, res) => {
  if (!Object.hasOwn(res, 'data')) {
    return res;
  }

  if (!Object.hasOwn(res.data, 'code')) {
    return res.data;
  }

  const { code } = res.data;
  const handleSwitches = [
    { condition: code >= 1000 && code < 2000, execute: handleSuccess },
    { condition: code >= 2000 && code <= 4000, execute: handleException },
    { condition: code === 4001, execute: handleLoginExpire },
    { condition: code === 4002, execute: handleTokenExpire },
    { condition: code === 4100, execute: handleLoginAgain },
    { condition: true, execute: handleException },
  ];

  const handle = handleSwitches.find(({ condition }) => condition);
  return handle ? handle.execute(http, res) : res;
};

const handleErrorFactory = (error) => {
  const httpCode = new Map();
  httpCode.set('ERR_BAD_OPTION_VALUE', '配置无效或不支持');
  httpCode.set('ERR_BAD_OPTION', '配置无效选项');
  httpCode.set('ECONNABORTED', '请求超时');
  httpCode.set('ETIMEDOUT', '请求超时');
  httpCode.set('ERR_NETWORK', '后端接口连接异常');
  httpCode.set('ERR_FR_TOO_MANY_REDIRECTS', '请求被重定次数过多');
  httpCode.set('ERR_DEPRECATED', '特性或方法已弃用');
  httpCode.set('ERR_BAD_RESPONSE', '无法正确解析响应或响应的格式无效');
  httpCode.set('ERR_BAD_REQUEST', '请求缺少必需的参数');
  httpCode.set('ERR_CANCELED', '功能或方法已由用户明确取消');
  httpCode.set('ERR_NOT_SUPPORT', '方法或特性不支持');
  httpCode.set('ERR_INVALID_URL', '请求URL无效');
  httpCode.set('ERR_REPEAT_SUBMIT', '提交过于频繁，请稍后再试');
  httpCode.set(400, '请求参数错误');
  httpCode.set(404, '请求地址不存在');
  httpCode.set(500, '服务器内部错误');

  const code = error.response?.status || error.code;
  if (httpCode.has(code)) {
    eventEmitter.emit('API:ERROR', httpCode.get(code));
  }

  return Promise.reject(error);
};

export const setupResponseInterceptor = (http) => {
  http.interceptors.response.use(function (res) {
    return handleFactory(http, res);
  }, handleErrorFactory);
};
